package com.namecard.namecardapi.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author wzx
 */
@Component
public class RedisUtil {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    public void saveListToRedis(String key, List<String> dataList, Integer validTime) {
        List<String> stringDataList = dataList.stream()
                .parallel()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        stringRedisTemplate.opsForList().rightPushAll(key, stringDataList);
        stringRedisTemplate.expire(key, validTime, TimeUnit.MINUTES);
    }


    public List<String> getListFromRedis(String key) {
        return stringRedisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 序列化java对象为json字符串，而不是一个String（这样子反序列化才能实现）
     */
    public void saveJsonStringToRedis(String key, List<?> dataList, Integer validTime) {
        List<String> stringDataList = dataList.stream()
                .parallel()
                .filter(Objects::nonNull)
                .map(data -> {
                    try {
                        return new ObjectMapper().writeValueAsString(data);
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                })
                .collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(key, stringDataList);
        stringRedisTemplate.expire(key, validTime, TimeUnit.MINUTES);
    }



}
